package com.github.lee.core.room

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.*
import androidx.datastore.preferences.createDataStore
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map


class DataStorePreferences(private val context: Context, private val fileName: String) {

    protected val dataStore: DataStore<Preferences> by lazy {
        context.createDataStore(fileName)
    }

    //===Desc:=========================================================


    suspend fun put(key: String, value: String) {
        dataStore.edit {
            it[stringPreferencesKey(key)] = value
        }
    }

    suspend fun put(key: String, value: Int) {
        dataStore.edit {
            it[intPreferencesKey(key)] = value
        }
    }

    suspend fun put(key: String, value: Double) {
        dataStore.edit {
            it[doublePreferencesKey(key)] = value
        }
    }

    suspend fun put(key: String, value: Float) {
        dataStore.edit {
            it[floatPreferencesKey(key)] = value
        }

    }

    suspend fun put(key: String, value: Long) {
        dataStore.edit {
            it[longPreferencesKey(key)] = value
        }
    }

    suspend fun put(key: String, value: Boolean) {
        dataStore.edit {
            it[booleanPreferencesKey(key)] = value
        }
    }

    //===Desc:=========================================================

    suspend fun getString(key: String, defaultValue: String? = null): String? =
        dataStore.data.map {
            it[stringPreferencesKey(key)] ?: defaultValue
        }.first()

    suspend fun getString(key: String, defaultValue: String? = null, block: (String?) -> Unit) {
        val result = dataStore.data.map {
            it[stringPreferencesKey(key)] ?: defaultValue
        }.first()
        block(result ?: defaultValue)
    }


    suspend fun getInt(key: String, defaultValue: Int? = null): Int? =
        dataStore.data.map {
            it[intPreferencesKey(key)] ?: defaultValue
        }.first()

    suspend fun getLong(key: String, defaultValue: Long? = null): Long? =
        dataStore.data.map {
            it[longPreferencesKey(key)] ?: defaultValue
        }.first()

    suspend fun getDouble(key: String, defaultValue: Double? = null): Double? =
        dataStore.data.map {
            it[doublePreferencesKey(key)] ?: defaultValue
        }.first()

    suspend fun getFloat(key: String, defaultValue: Float? = null): Float? =
        dataStore.data.map {
            it[floatPreferencesKey(key)] ?: defaultValue
        }.first()

    suspend fun getBoolean(key: String, defaultValue: Boolean? = null): Boolean? =
        dataStore.data.map {
            it[booleanPreferencesKey(key)] ?: defaultValue
        }.first()

}

